package com.hiyee.goods.service.impl;

import com.github.pagehelper.PageHelper;
import com.hiyee.goods.mapper.GoodsMapper;
import com.hiyee.goods.mapper.ProductMapper;
import com.hiyee.goods.repository.GoodsRepo;
import com.hiyee.goods.service.GoodsService;
import com.hiyee.pojo.Goods;
import com.hiyee.pojo.Product;
import com.hiyee.pojo.bo.GoodsSearchBO;
import com.hiyee.pojo.repo.GoodsInfoRepo;
import com.hiyee.pojo.vo.CustomerGoodsInfoVO;
import com.hiyee.pojo.vo.GoodsSearchListVO;
import com.hiyee.response.PagedGridResult;
import com.hiyee.utils.PageGridResultUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private GoodsRepo goodsRepo;
    @Autowired
    private ProductMapper productMapper;

    @Override
    public PagedGridResult search(GoodsSearchBO goodsSearchBO) {
        Example example = new Example(Goods.class);
        example.selectProperties("goodsId", "name", "goodsBn", "goodsType", "marketPrice", "salesPrice", "videoUrl", "imageUrl");
        Example.Criteria criteria = example.createCriteria();
        // 查询条件
        if(goodsSearchBO.getCategoryId() != null && goodsSearchBO.getCategoryId() > 0) {
            criteria.andEqualTo("categoryId", goodsSearchBO.getCategoryId());
        }
        if(!StringUtils.isEmpty(goodsSearchBO.getName())) {
            criteria.andLike("name", "%" + goodsSearchBO.getName() + "%");
        }
        if(!StringUtils.isEmpty(goodsSearchBO.getSortType()) && !StringUtils.isEmpty(goodsSearchBO.getSortBy())) {
            switch (goodsSearchBO.getSortBy()) {
                case "all":
                case "sales":
                    example.setOrderByClause("sold_num desc");
                    break;
                case "price":
                    example.setOrderByClause("sales_price " + goodsSearchBO.getSortType());
                    break;
            }
        }
        PageHelper.startPage(goodsSearchBO.getPage(), goodsSearchBO.getPageSize());
        List<Goods> adminUserList = goodsMapper.selectByExample(example);
        return PageGridResultUtil.getPageGridResult(adminUserList, goodsSearchBO.getPage());
    }

    @Override
    public GoodsInfoRepo getInfo(Long id) {
        return goodsRepo.getById(id);
    }

    @Override
    public Product getProduct(Long id) {
        Example example = new Example(Product.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("productId", id);
        return productMapper.selectOneByExample(example);
    }
}
